// VC10.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "VC10.h"
#include "VC10Dlg.h"
#include "RegistrationDlg.h"

#include "..\RMSLib\Registration.h"
#include "..\RMSLib\Registry.h"
#include "..\Common\XMessageBox.h"
#include "CamSelect.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#ifdef _NET_VC_

#ifndef _VC_J7_
	#define APP_NAME	"NetVC Viewer"
#else
	#define APP_NAME	"VC-J7 Viewer"
#endif

#elif defined VC70
	#define APP_NAME	"VC-70 Viewer"
#else
	#define APP_NAME	"VC-10 Viewer"
#endif

#ifdef _RMS_TOML_
  #include <clientthr.h>
  CAuthClient* pAuthClient;
  CLog* pLog;
  string gUserLogin;
  string gUserPassword;
  string gServerIP;
#endif

HWND ghDlg;				// Handle to main dialog box
HACCEL ghAccelTable;	// Handle to accelerator table

/////////////////////////////////////////////////////////////////////////////
// CVC10App

BEGIN_MESSAGE_MAP(CVC10App, CWinApp)
	//{{AFX_MSG_MAP(CVC10App)
	//}}AFX_MSG
	ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CVC10App construction

CVC10App::CVC10App()
{
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CVC10App object

CVC10App theApp;

/////////////////////////////////////////////////////////////////////////////
// CVC10App initialization

bool gUserModeEnabled=false;

#include "../Common/sfec.h"

BOOL CVC10App::InitInstance()
{
    gUserModeEnabled = false;

    string s(m_lpCmdLine);
    pCmdLine = new CSimpleCmdLine(s);

    gBufSize = pCmdLine->GetIntParam("buf", gBufSize);
    gVolume = pCmdLine->GetIntParam("volume", gVolume);

    gCallerWindowHandle = (HWND) pCmdLine->GetIntParam("wh", (int) gCallerWindowHandle);
    gNotifyPeriod = pCmdLine->GetIntParam("duration", gNotifyPeriod);
    gNotifyMsgID = pCmdLine->GetIntParam("mid", gNotifyMsgID);
    gNotifyClientID = pCmdLine->GetIntParam("cid", gNotifyClientID);

    if(pCmdLine->GetParam("stats"))
      gDisplayStats = pCmdLine->GetIntParam("stats", -1);

#ifdef _GUI2008_
    gUserModeEnabled = !pCmdLine->GetParam("admin");
/*
    gUserModeEnabled = true;
    string s1=s;
    transform(s1.begin(), s1.end(), s1.begin(), tolower);

    if (s1.substr(0, 5)=="admin")
    {
      gUserModeEnabled = false;
      if(s.length()>=6)
      {
        s = s.substr(6); // remove "admin " at the beginning of command line
        s.copy(m_lpCmdLine, 160); // store result back to cmdline variable
      }
    }*/
#endif

//#define EXPIRED 
#ifdef _OEM_
	#ifndef _TEC_
		#define EXPIRED
	#endif
#endif
#ifdef EXPIRED

#ifdef _OEM_
	int MAX_DAYS=30;
	SetRegistryKey("Streambox_OEM");
#else
	int MAX_DAYS=7;
//	int MAX_DAYS=30;
	SetRegistryKey("Streambox");
#endif

    int RunTime;
    int DaysLeft=MAX_DAYS;

    RunTime = GetProfileInt("","run0",-1);
    DaysLeft = GetProfileInt("","run1",-1);

    bool bExpired=false;
    int day;
    
    if (RunTime!=-1) {
        if (abs(time(0)-RunTime) > 24*3600) {
            DaysLeft -= abs(time(0)-RunTime) / (24*3600);
            WriteProfileInt("","run0",time(0));
            WriteProfileInt("","run1",DaysLeft);
        }
        
        if (DaysLeft<=0)
            bExpired=true;
    }
    else {
        WriteProfileInt("","run0",time(0));
        WriteProfileInt("","run1",MAX_DAYS);
        DaysLeft=MAX_DAYS;
    }


    if (bExpired) {
         MessageBox(NULL, _T("The application has expired. Please contact \nsupport@streambox.com for more information."),
					_T(APP_NAME), MB_OK | MB_ICONWARNING);
         return FALSE;
    }
    else {
        char szTrialMessage[100];
        sprintf(szTrialMessage,"You are on day %d of your %d-day trial period\n\nOnly %d day(s) left to buy a full version",MAX_DAYS+1-DaysLeft,MAX_DAYS,DaysLeft);
               
        
        if (XMessageBox(NULL,szTrialMessage,"Trial Reminder",MB_STARTBUY | MB_NORESOURCE,0)==IDBUY) {
            ShellExecute(0,"open","http://www.streambox.com","","",SW_SHOW);
            return FALSE;            
        }    
    }
#else
	bool bRegistration = false;

	LPCTSTR MyAppName = ::AfxGetAppName();
	if (stricmp(MyAppName, "VC-J7NP") == 0) {
		bRegistration = false; // This code makes VC-J7 viewer copy free requested by Mr. Hiroshi Hasegawa.
	}

 #ifndef _OEM_
  #ifdef _NET_VC_
   #ifndef _HCP_
    #ifndef _QFI_NCP_
	CTime Time = CTime::GetCurrentTime();
 	CTime haltTime(2010, 12, 31, 23, 59, 59);
  	if(Time >= haltTime){
  		MessageBox(NULL, _T("The application has expired. Please contact \n"
							"support@streambox.com for more information."),
						 _T(APP_NAME), MB_OK | MB_ICONWARNING);
  		return FALSE;
  	}
    #endif //ndef _QFI_NCP_
   #endif //ndef _HCP_
  #endif //def _NET_VC_
 #endif //ndef _OEM_

	SetRegistryKey("Streambox");

	// Registration key
	char szName[256];
	char szKey[KEY_LENGTH+1];

   if(bRegistration)
   {
	if(REGISTRY_LoadString(KEY_REGISTRATION_NAME, szName, 256))
	{
		if(REGISTRY_LoadString(KEY_REGISTRATION_KEY, szKey, KEY_LENGTH+1))
		{
			if(CheckKey(szName, szKey))
			{
				bRegistration = false;
			}
		}
	}
   }
#ifdef _J707_PENDING_ //#J7070020
	bRegistration = false;
#endif
	if(bRegistration)
	{
		CRegistrationDlg dlg;
		int count = 0;
		while(count < 5)
		{
			if(dlg.DoModal() == IDOK)
			{
				if(CheckKey(static_cast<LPCTSTR>(dlg.m_strName), static_cast<LPCTSTR>(dlg.m_strKey)))
				{
					bRegistration = false;
					REGISTRY_SaveString(KEY_REGISTRATION_NAME, static_cast<LPCTSTR>(dlg.m_strName));
					REGISTRY_SaveString(KEY_REGISTRATION_KEY, static_cast<LPCTSTR>(dlg.m_strKey));
					break;
				}
				else
				{
					MessageBox(NULL, _T("Registration key is not valid."), _T(APP_NAME), MB_OK | MB_ICONWARNING);
				}
			}
			else
			{
				return FALSE;
			}
			count++;
		}
	}

	if(bRegistration) return FALSE;
#endif

#ifdef _OEM_
#ifndef _TEC_
	CTime Time = CTime::GetCurrentTime();
 	CTime haltTime(2003, 4, 20, 0 , 0, 0);
  	if(Time >= haltTime){
  		MessageBox(NULL, _T("The application has expired. Please contact \nsupport@streambox.com for more information."),
				   _T(APP_NAME), MB_OK | MB_ICONWARNING);
  		return FALSE;
  	}
#endif
#endif
	WORD wVersionRequested;
	WSADATA wsaData;
 
	wVersionRequested = MAKEWORD( 2, 0 );
 
	WSAStartup( wVersionRequested, &wsaData );
	
	AfxEnableControlContainer();

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	//  of your final executable, you should remove from the following
	//  the specific initialization routines you do not need.

#ifdef _AFXDLL
	Enable3dControls();			// Call this when using MFC in a shared DLL
#else
	Enable3dControlsStatic();	// Call this when linking to MFC statically
#endif

	////////////////////////////////////////
	// AUDIO

	//CString AudioDriverName = GetProfileString("Settings", "Audio");
	CString strAudioDriverName = GetProfileString( GetOptionsSectionName(), GetAudioOptionsSubSectionName() );
	if (0 == strAudioDriverName.GetLength())
	{
		// add default driver
		m_strAudioDriverName = "WaveOutDriver";
		WriteProfileString(GetOptionsSectionName(), GetAudioOptionsSubSectionName(), m_strAudioDriverName.c_str());


	
	} else
	{

		m_strAudioDriverName = (LPCSTR)strAudioDriverName;
	}

	ghAccelTable = LoadAccelerators(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_ACCELERATOR));

#ifdef _RMS_TOML_
  InitFoo();
  pLog = new CLog("vc70view.log");
  // load login/password:
  int i;
  FILE* f;
  char buf[256];
  f = fopen("userinfo.dat","r");
  gUserLogin = "default";
  gUserPassword = "none";
  gServerIP = "127.0.0.1";
  if(f==NULL)
  {
    _log(strtime() << "ERROR: could'n open userinfo.dat file\n");
    _log(strtime() << "Applying defaults.\n");
  } else
  if(fgets(buf, 255, f))
  {
    string s(buf);
    while((s.size()>0)&& ( (s[s.size()-1]=='\n')||(s[s.size()-1]=='\r') ) ) s.erase(s.size()-1);
    i = s.find('/');
    if(i==string::npos)
    {
      gUserLogin = s.substr(0,16);
      gUserPassword = "none";
    } else
    {
      gUserLogin = s.substr(0,i).substr(0,16);
      gUserPassword = s.substr(i+1).substr(0,16);
    }
    if(fgets(buf, 255, f))
      gServerIP = buf;
  }
  pAuthClient = new CAuthClient(ctViewer, gUserLogin, gUserPassword, gServerIP);
#endif




	CVC10Dlg dlg;
	m_pMainWnd = &dlg;
	int nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
	}
	else if (nResponse == IDCANCEL)
	{
	}

	// Since the dialog has been closed, return FALSE so that we exit the
	//  application, rather than start the application's message pump.
	return FALSE;
}

int CVC10App::ExitInstance() 
{
  if (pCmdLine!=NULL) delete pCmdLine;

#ifdef _RMS_TOML_
	if(pAuthClient) delete pAuthClient;
	if(r1CSinitialized) DeleteCriticalSection(&r1CS);
#endif
	// save Audio settings 
	CString AudioDriverName = GetProfileString( GetOptionsSectionName(), GetAudioOptionsSubSectionName() );
	if(AudioDriverName.IsEmpty())
	{
		WriteProfileString(GetOptionsSectionName(), GetAudioOptionsSubSectionName(), m_strAudioDriverName.c_str());
	} else
	{
		String aaa = (LPCSTR)AudioDriverName;
		if(m_strAudioDriverName != aaa)
		{
			WriteProfileString(GetOptionsSectionName(), GetAudioOptionsSubSectionName(), m_strAudioDriverName.c_str());
		}
	}
	

	return CWinApp::ExitInstance();
}

BOOL CVC10App::ProcessMessageFilter(int code, LPMSG lpMsg)
{
	if(code < 0)
		return CWinApp::ProcessMessageFilter(code, lpMsg);

	if(ghDlg && ghAccelTable)
	{
		if(::TranslateAccelerator(ghDlg, ghAccelTable, lpMsg))
			return TRUE;
	}

	return CWinApp::ProcessMessageFilter(code, lpMsg);
}
